package com.kczd.jinlan.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.normaladapter.ConfirmOrderAdapter;
import com.kczd.jinlan.model.ShoppingCartBean;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.view.mine.LocationActivity;
import com.kczd.jinlan.view.shopcar.ShoppingActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 确认订单页面
 */
public class ConfirmOrderActivity extends AppCompatActivity implements ConfirmOrderAdapter.PriceNumcallBack,View.OnClickListener{
    private static final String TAG="ConfirmOrderActivity.class";
    private ListView listView;
    public  List<ShoppingCartBean> dataList = new ArrayList<>();
    private TextView mPrice,mSub_order;
    ConfirmOrderAdapter confirmOrderAdapter;
    private List<ShoppingCartBean> listcar=ShoppingActivity.alreadyShoplist;
    String carjson="";
    private TextView tv_username;
    private TextView tv_phone_num;
    private TextView tv_address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);

        tv_username= (TextView) findViewById(R.id.ed_username);
        tv_phone_num= (TextView) findViewById(R.id.id_phone_num);
        tv_address= (TextView) findViewById(R.id.address_id);

        StringBuilder stringBuilder=new StringBuilder();
        for(int i=0;i<listcar.size();i++)
        {
            ShoppingCartBean shoppingCartBean=listcar.get(i);
            stringBuilder.append(shoppingCartBean.toString()+",");
        }
        String json=stringBuilder.toString();
        //去掉最后一个逗号
        String jsonStr= json.substring(0,json.length()-1);
        carjson="["+jsonStr+"]";
        new Thread(new Runnable() {
            @Override
            public void run() {
                getShopcardata(carjson);
            }
        }).start();

        listView= (ListView) findViewById(R.id.id_shop_detail);
        confirmOrderAdapter=new ConfirmOrderAdapter(listcar);
        confirmOrderAdapter.setPriceNumcallBack(this);
        listView.setAdapter(confirmOrderAdapter);

        mPrice= (TextView) findViewById(R.id.id_price);
        mSub_order= (TextView) findViewById(R.id.tv_suborder);
        mSub_order.setOnClickListener(this);

        //跳转到地址页面
        findViewById(R.id.id_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ConfirmOrderActivity.this, LocationActivity.class));
            }
        });
    }

    String url=Config.net_addr+"order/index";
    String commiturl=Config.net_addr+"order/sub_order";
    public void getShopcardata(String carjson)
    {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("token", Config.user.getToken())
                .add("cartlist", carjson)
                .build();
        Log.e(TAG,"token"+Config.user.getToken());
        Log.e(TAG,"cartlist"+carjson);
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))){
                    JSONObject js=jsonResult.getJSONObject("data");
                    JSONArray jsonArray=js.getJSONArray("address_list");
                    for(int i=0;i<jsonArray.length();i++)
                    {
                        String is_default= jsonArray.getJSONObject(i).getString("is_default");
                        if(is_default.equals("1"))//默认地址
                        {
                            String username=jsonArray.getJSONObject(i).getString("consignee");
                            String province=jsonArray.getJSONObject(i).getString("province");
                            String city=jsonArray.getJSONObject(i).getString("city");
                            String district=jsonArray.getJSONObject(i).getString("district");
                            String town=jsonArray.getJSONObject(i).getString("town");
                            String address=jsonArray.getJSONObject(i).getString("address");
                            String mobile=jsonArray.getJSONObject(i).getString("mobile");
                            tv_username.setText(username);
                            tv_phone_num.setText(mobile);
                            tv_address.setText(province+city+district+address);
                        }
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭页面的时候，将购物车信息重置为空
        ShoppingActivity.alreadyShoplist.clear();
    }

    /**
     * 显示价钱的回调接口
     * @param price
     */
    @Override
    public void showPrice(String price) {
        mPrice.setText(price);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //提交订单
            case R.id.tv_suborder:

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        commitOrder();
                    }
                }).start();

                break;
        }
    }

    public void commitOrder(){
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("token", Config.user.getToken())
                .add("cartlist", carjson)
                .add("freight_price","6")//运费
                .add("goods_price",mPrice.getText().toString())//商品总价
                .add("total_price",mPrice.getText().toString())//订单总价
                .add("address_id","")//收货地址id
                .build();
        Request request=new Request.Builder()
                .url(commiturl)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            comithandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler comithandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))){

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
}
